package com.cz.fra.dao.security;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.cz.fra.dao.EntityNotFoundException;
import com.cz.fra.dao.PersistenceException;
import com.cz.fra.entity.User;
import com.cz.fra.utils.DBUtil;

public class JdbcSecurityDao implements SecurityDao{

	private DBUtil dbUtil = new DBUtil();
	
	@Override
	public User getUserData(String userName, String userPassword)
			throws PersistenceException, EntityNotFoundException {
		User user = null;
		String login_auth_sql = "select * from "+ DBUtil.databaseName +".frs_user where username = '"+userName+"' and password = '"+userPassword+"'";
		ResultSet rs = null;
		dbUtil.getConnection();
		try {
			rs = dbUtil.executeQuery(login_auth_sql);
			if(rs.next()){
				user = mapRow(rs);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			dbUtil.closeConnection();
		}
		return user;
	}
	
	public User mapRow(ResultSet rs) throws SQLException{
		User user = new User();
		
		user.setUserid(rs.getInt("user_id"));
		user.setUsername(rs.getString("username"));
		user.setPassword(rs.getString("password"));
		user.setEmail(rs.getString("email"));
		user.setCreateDate(rs.getTimestamp("register_date"));
		user.setAddress(rs.getString("address"));
		
		return user;
	}
}
